package com.wangt.biz.socket;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author gongtan
 */
@Slf4j
public class TCPClient {
    public static Bootstrap bootstrap = getBootstrap();

    // 初始化Bootstrap
    public static Bootstrap getBootstrap() {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class);
        b.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
                pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
                pipeline.addLast("handler", new TCPClientHandler());
            }
        });
        b.option(ChannelOption.SO_KEEPALIVE, true);
        return b;
    }

    public static Channel connectToServer(String host, int port) {
        Channel channel = null;
        try {
            channel = bootstrap.connect(host, port).sync().channel();
        } catch (Exception e) {
            log.error("协议==> TCP客户端连接服务({}:{})失败", host, port, e);
            return null;
        }

        TCPCache.INSTANCE.getServerInfoContext().put(host + ":" + port, channel);
        return channel;
    }

    public static void sendMsg(String host, int port, Object data) throws Exception {
        Channel channel = TCPCache.INSTANCE.getServerInfoContext().get(host + ":" + port);
        if (channel != null) {
            channel.writeAndFlush(data).sync();
        } else {
            log.warn("协议==> TCP客户端消息发送失败，因为连接尚未建立!");
        }
    }
}
